package xmlParser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

public class SAXHandler0 extends DefaultHandler{
	
	public HashMap<String,List<SAXBean>> fMap = new HashMap();
	private Stack<Object[]> fStack = new Stack();
	private StringBuilder fBuilder = new StringBuilder();
	private int fCounter  = 0;
	
	public SAXHandler0(){
		
	}
	
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		Object[] objs = new Object[3];
		objs[0] = qName;
		objs[1] = new AttributesImpl(atts);
		objs[2] = fCounter++;
		fStack.push(objs);
		fBuilder.setLength(0);
	}
	
	public void characters(char ch[], int start, int length)
	throws SAXException {
		fBuilder.append(new String(ch,start,length));
	}
	
	public void endElement(String uri, String localName, String qName)
	throws SAXException {
		Object[] path = getPath();
		List list = fMap.get(path[0]);
		if(list==null){
			list = new ArrayList();
			fMap.put((String)path[0], list);
		}
		SAXBean bean = new SAXBean();
		bean.fValue = fBuilder.toString();
		bean.fPosition = (Integer[])path[1];
		bean.path = (String)path[0];
		list.add(bean);
		
		Object[] objs = fStack.pop();
		bean.fAttributes = (AttributesImpl)objs[1];
		fBuilder.setLength(0);
	}
	
	public Object[] getPath(){
		int size = fStack.size();
		Object[] result = new Object[2];
		Integer[] position = new Integer[size]; 
		StringBuilder sb = new StringBuilder(100);
		for(int i=0;i<size;i++){
			Object[] objs = fStack.get(i);
			position[i] = (Integer)objs[2];
			String obj = (String)objs[0];
			sb.append("/")
			.append(obj);
		}
		result[0] = sb.toString();
		result[1] = position;
		return result;
	}
	
}
